package com.znsd.zl.app.user.utils;

import com.znsd.zl.app.user.entity.AppUserEntity;
import com.znsd.zl.utils.DateUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * <p>
 *      JWT工具类
 * </p>
 * @ClassName IAppUserService
 * @Description 客户端用户业务层接口
 * @author jaypdd
 * @email jaypdd@163.com
 * @date 2020-08-24 16:26:01
 * @Version v1.0
 */
@ConfigurationProperties(prefix = "zlhouse.jwt")
@Component
@Data
public class JwtUtils {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private String secret;
    private long expire;
    private String header;

    /**
     * 生成jwt token
     */
    public String generateToken(String credentials) {
        Date nowDate = new Date();
        //过期时间
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(credentials)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 获取token，对token进行解密
     * @param token 解密的Token
     * @return
     */
    public Claims getClaimByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            logger.debug("validate is token error ", e);
            return null;
        }
    }

    /**
     * token是否过期
     * @return  true：过期
     */
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }

    /**
     * 生成token
     * @param userId        用户id
     * @param openId        openid
     * @param sessionKey    sessionKey
     * @return              返回token
     */
    public String createToken(Integer userId, String openId, String sessionKey) {
        // 封装用户凭证
        StringBuilder credentials = new StringBuilder();
        credentials.append(userId)
                .append("#").append(sessionKey)
                .append("#").append(openId);
        // 生成token
        String token = generateToken(credentials.toString());
        return token;
    }

    /**
     * token令牌解密
     * @param token 解密的token
     * @return      返回token中的userId(0)，openId(2)，与session_key(1)
     */
    public String[] tokenDecode(String token) {
        int tokenSize = 2;
        Claims claimByToken = getClaimByToken(token);
        if ( token != null && claimByToken != null ) {
            String[] info = claimByToken.getSubject().split("#");
            if ( info.length > tokenSize ) {
                return info;
            }
        }
        return null;
    }

}
